<!--多选项目保存设备权限-->
<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-row :gutter="10">
      <a-col :span="10">
        <a-card title="项目权限" :bodyStyle="bodyStyle">
          <user-project-permission-modal :tenantId="tenantId" :userId="userId" ref="userProjectPermissionModal" @selectProject="selectProject"></user-project-permission-modal>
        </a-card>
      </a-col>
      <a-col :span="14">
        <a-card title="设备权限">
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchQuery" >
              <a-row :gutter="24">
                <a-col :md="6" :sm="12">
                  <a-form-item label="设备ID">
                    <j-input placeholder="" v-model="queryParam.id"></j-input>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="12">
                  <a-form-item label="设备名称">
                    <j-input placeholder="" v-model="queryParam.name"></j-input>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="12">
                  <a-form-item label="设备序列号">
                    <j-input placeholder="" v-model="queryParam.devSerialNo"></j-input>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="12">
                  <a-button type="primary" icon="search" @click="searchQuery">搜索</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>

          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <span slot="action" slot-scope="text, record">
              <j-checkbox v-model="sport[record.projectId+'_'+record.id]" :options="record.funs" @change="onChange($event, record.id)"></j-checkbox>
            </span>

          </a-table>
        </a-card>
      </a-col>
    </a-row>

  </j-modal>
</template>

<script>
  import { api, listUserDevice } from './service'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import JCheckbox from '@/components/jeecg/JCheckbox'
  import UserProjectPermissionModal from './UserProjectPermissionModal.vue'

  export default {
    name: 'UserDeviceModalCheck0418',
    mixins: [JeecgListMixin],
    components: {
      JCheckbox,
      UserProjectPermissionModal
    },
    data () {
      return {
        title: '项目设备权限设置',
        width: 1400,
        visible: false,
        bodyStyle: { 'min-height': '500px' },

        disableMixinCreated: true,
        tenantId: '',
        userId: '',
        projectId: '',

        // 表头
        columns: [
          {
            title: '设备ID',
            dataIndex: 'id'
          },
          {
            title: '设备名称',
            dataIndex: 'name'
          }, {
            title: '设备序列号',
            dataIndex: 'devSerialNo'
          }, {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' }
          }
        ],
        dataSource: [],

        sport: {},
        projectUserDeviceMap: {},

        url: {
          list: ''
        }
      }
    },
    methods: {
      show(tenantId, userId) {
        let that = this;
        this.tenantId = tenantId;
        this.userId = userId;
        this.visible = true;

        this.dataSource = []
        this.url.list = ''
        this.queryParam = {}
        this.sport = {}
        this.projectUserDeviceMap = {}
        let params = { tenantId: that.tenantId }
        listUserDevice(userId, params).then(res => {
          if (res.success) {
            res.result.forEach(function (item) {
              let cacheUserDeviceMap = that.projectUserDeviceMap[item.projectId];
              if (cacheUserDeviceMap === undefined) {
                cacheUserDeviceMap = {};
              }
              cacheUserDeviceMap[item.deviceId] = item;
              that.projectUserDeviceMap[item.projectId] = cacheUserDeviceMap;
              let authJoin = item.newAuths.join(',');
              if (authJoin) {
                let sportKey = item.projectId + '_' + item.deviceId;
                that.sport[sportKey] = authJoin
              }
            })
          }
        });
      },
      handleOk () {
        /* let that = this;
        let param = []
        for (let projectId in that.projectUserDeviceMap) {
          let cacheUserDeviceMap = that.projectUserDeviceMap[projectId];
          for (let deviceId in cacheUserDeviceMap) {
            let device = cacheUserDeviceMap[deviceId];
            let sportKey = projectId + '_' + deviceId;
            if (that.sport[sportKey] !== undefined) {
              device.newAuths = that.sport[sportKey].trim(',').split(',');
              device.userId = that.userId;
              device.tenantId = that.tenantId
              param.push(device)
            }
          }
        }
        if (param.length === 0) {
          that.$message.warn('请选择设备功能');
        } else {
          let url = that.url.saveUserDevice;
          putAction(url, param).then(res => {
            if (res.success) {
              that.$message.success('保存成功');
              that.close()
            } else {
              that.$message.error(res.message);
            }
          });
        } */
        let map = this.projectUserDeviceMap;
        let sport = this.sport;
        console.log(map);
        console.log(sport);
      },
      handleCancel () {
        this.close()
      },
      close () {
        this.visible = false;
      },
      searchQuery() {
        if (!this.url.list) {
          this.$message.warning('请先选中项目！')
          return
        }
        this.loadData(1);
        this.getUserDevice();
      },
      selectProject(projectId) {
        this.url.list = api.listDevicesByProjId(projectId);
        this.projectId = projectId;
        this.searchQuery();
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;

        let cacheUserDeviceMap = this.projectUserDeviceMap[this.projectId];
        if (cacheUserDeviceMap === undefined) {
          cacheUserDeviceMap = {}
        }
        let userDeviceMap = {}
        for (let deviceId in cacheUserDeviceMap) {
          if (selectedRowKeys.indexOf(deviceId) !== -1) {
            userDeviceMap[deviceId] = cacheUserDeviceMap[deviceId]
          }
        }

        let selectionRowsMap = {}
        selectionRows.forEach((item) => {
          selectionRowsMap[item.id] = item
        })

        selectedRowKeys.forEach((deviceId) => {
          let funsArr = selectionRowsMap[deviceId].funs;
          let funIdArr = [];
          if (funsArr.length > 0) {
            funsArr.forEach((fun) => {
              funIdArr.push(fun.id);
            })
          }
          if (userDeviceMap[deviceId] === undefined) {
            userDeviceMap[deviceId] = {
              projectId: selectionRowsMap[deviceId].projectId,
              projectUuid: selectionRowsMap[deviceId].projectUuid,
              deviceId: selectionRowsMap[deviceId].id,
              deviceUuid: selectionRowsMap[deviceId].uuid,
              newAuths: funIdArr
            }
          }
          let sportKey = this.projectId + '_' + deviceId
          this.sport[sportKey] = funIdArr.join(',')
          this.sport = Object.assign({}, this.sport)
        });
        cacheUserDeviceMap = userDeviceMap;
        this.projectUserDeviceMap[this.projectId] = cacheUserDeviceMap
      },
      getUserDevice () {
        /* let that = this
        let url = this.url.getUserDevice.replace('{tenant_id}', that.tenantId)
                                      .replace('{user_id}', that.userId);
        getAction(url).then(res => {
          if (res.success) {
            let keys = []
            that.userDeviceMap = {}
            res.result.forEach(function (item) {
              keys.push(item.deviceId + '');
              that.userDeviceMap[item.deviceId] = item

              let authJoin = item.newAuths.join(',')
              if (authJoin) {
                that.sport[item.deviceId] = authJoin
              }
            })
            that.selectedRowKeys = keys
          }
        }); */

        let cacheUserDeviceMap = this.projectUserDeviceMap[this.projectId];
        if (cacheUserDeviceMap === undefined) {
          cacheUserDeviceMap = {};
        }
        let keys = []

        for (let deviceId in cacheUserDeviceMap) {
          let item = cacheUserDeviceMap[deviceId];
          keys.push(item.deviceId + '');
          let authJoin = item.newAuths.join(',');
          if (authJoin) {
            let sportKey = this.projectId + '_' + item.deviceId;
            this.sport[sportKey] = authJoin
          }
        }
        this.selectedRowKeys = keys
      },
      reWriterWithSlot(arr) {
        for (let item of arr) {
          if (item.children && item.children.length > 0) {
            this.reWriterWithSlot(item.children)
            let temp = Object.assign({}, item)
            temp.children = {}
            this.projectTree.push(temp)
          } else {
            this.projectTree.push(item)
            item.scopedSlots = { title: 'title' }
          }
        }
      },
      onChange(values, deviceId) {
        let that = this;
        let sportKey = this.projectId + '_' + deviceId
        that.sport[sportKey] = values
        that.sport = Object.assign({}, this.sport)
        that.dataSource.forEach(function (item) {
          if (item.id === deviceId) {
            that.deviceChange(item, values)
          }
        })
      },
      deviceChange(record, auths) {
        let that = this
        let deviceId = record.id
        let sportKey = record.projectId + '_' + deviceId;
        let values = that.sport[sportKey];
        let idx = this.selectedRowKeys.indexOf(deviceId);
        let cacheUserDeviceMap = that.projectUserDeviceMap[record.projectId];
        if (cacheUserDeviceMap === undefined) {
          cacheUserDeviceMap = {};
        }
        if (values) {
            that.selectedRowKeys.push(deviceId);
            cacheUserDeviceMap[deviceId] = {
              projectId: record.projectId,
              projectUuid: record.projectUuid,
              deviceId: record.id,
              deviceUuid: record.uuid,
              newAuths: auths.trim(',').split(',')
            }
        } else {
          if (idx !== -1) {
            that.selectedRowKeys.splice(idx, 1);
            delete cacheUserDeviceMap[deviceId];
          }
        }
        that.projectUserDeviceMap[record.projectId] = cacheUserDeviceMap;
      }
    }
  }
</script>

<style scoped>
  /deep/ .ant-tree li span.ant-tree-switcher{
    display: none;
  }
</style>
